<template>
  <div class="app-container">

   <el-card class="marginTop20">
    <div class="title-top flex-between">
       <div class="title-top-fl">{{form.companyName}}</div>
     <div class="title-top-fr" style="color: #2158F3;cursor: pointer;" @click="allIsTap" v-if="allIs"> 收起<el-icon><CaretTop /></el-icon></div>
     <div class="title-top-fr" style="color: #2158F3;cursor: pointer;" @click="allIsTap" v-else> 展开<el-icon><CaretBottom /></el-icon></div>

    </div>
    <div class="xlMain" v-show="allIs">
       <div class="xlMain-list">
          <div class="xlMain-lable"><el-icon color="#22A86D"><LocationFilled /></el-icon>出发城市</div>
          <div class="xlMain-lable">箱贴单价</div>
          <div class="xlMain-lable">预还量</div>
          <div class="xlMain-lable"><el-icon color="#FF4B40"><LocationFilled /></el-icon>到达城市</div>
       </div>
       <div class="xlMain-list" v-for="(item, index) in priceList" :key="index">
          <div class="xlMain-lable">
                <el-select id="el-select " v-if="index==0" v-model="carryCityInfo.cityId" style="width:40%" placeholder="请选择">
                  <el-option v-for="item in carryCityList" :key="item.cityId" :label="item.cityName" :value="item.cityId" />
                </el-select>
          </div>
          <div class="xlMain-lable">
             <el-input
              v-model.trim="item.unitPrice"
              :formatter="formatterNumber" :parser="formatterNumber"
                placeholder="请输入"
                class="input-with-select"
                maxlength="8"
                clearable
              >
                <template #prepend>$</template>>
              </el-input>
          </div>
          <div class="xlMain-lable">
            <el-input-number v-model.trim="item.boxQuantity" :min="0" maxlength="8"  />

          </div>
          <div class="xlMain-lable flex-cen">
             <el-select style="width:220px" @change="returnCityIdChang(item.cityId,index)" clearable v-model="item.returnCityId" placeholder="请选择">
                  <el-option v-for="item in returnCityList" :label="item.cityName" :value="item.cityId"
                    :key="item.cityId" />
                </el-select>
            <el-icon color="#D8D8D8" size="20px" style="margin-left: 20px;" @click="handleDelete(index,1)"><Remove /></el-icon>
          </div>

       </div>
       <div class="xlMain-list">
         <div class="xlMain-lable">
          </div>
          <div class="xlMain-lable" style="text-align: left;">
            <el-icon color="#2158F3" size="20px" @click="handleAdd(1)"><CirclePlus /></el-icon>
          </div>

       </div>
       <div class="zlAmo">总量：{{totalNumber}}个</div>
    </div>
   </el-card>
   <el-card class="marginTop20">
    <span class="_before">订单消息</span>
    <div class="mian-cen">
      <div class="mian-cen-top">
        <div class="mian-cen-top-fl">
          <img :src="mainFileList[0]?.url" style="width: 300px;margin-right: 20px;" />
        </div>
         <div class="mian-cen-top-fr">
            <div  class="mian-cen-list">
              <div class="mian-cen-item">
                <div class="item-label">箱型：</div>
                <div class="item-value">{{ { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }[dataInfo.boxType] }}</div>
              </div>


              <div class="mian-cen-item">
                <div class="item-label">箱况：</div>
                <div class="item-value">{{ { 5: '全新', 10: '次新', 15: '适货', 20: '混提' }[dataInfo.boxCondition] }}</div>
              </div>
              <div class="mian-cen-item">
                <div class="item-label">箱使期：</div>
                <el-input  v-model="form.boxUsagePeriod" :formatter="formatterNumber" :parser="formatterNumber" :min="0" :max="999" :precision="0"  placeholder="请输入箱使期" maxlength="5" >
                  <template #append>天</template>
                </el-input>
              </div>
            </div>
            <div  class="mian-cen-list">
              <div class="mian-cen-item">
                <div class="item-label red-star">预计提箱日期：</div>
                <div class="item-value">
            <el-date-picker type="date" v-model="form.planPickupDate" placeholder="请选择日期" clearable />
<!-- 
                  <el-date-picker v-model="param.createDate" type="date" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" /> -->
                </div>
              </div>
              <div class="mian-cen-item">
                <div class="item-label red-star">支付方式：</div>
                <el-select placeholder="请选择" clearable v-model="form.paymentMethod">
                  <el-option label="对公转账" value="5" />
                  <el-option label="在线支付" value="10" />
                </el-select>
              </div>
              <div class="mian-cen-item">
                <div class="item-label">结算账期：</div>
                <el-input v-model="form.period" :formatter="formatterNumber" :parser="formatterNumber" placeholder="请输入结算账期" maxlength="5" >
                  <template #append>天</template>
                </el-input>
              </div>
            </div>
            <div  class="mian-cen-list">
              <div class="mian-cen-item">
                <div class="item-label">联系人：</div>
                <div class="item-value">{{form.publisherName  || '--'}}</div>
              </div>
              <div class="mian-cen-item">
                <div class="item-label">联系电话：</div>
                <div class="item-value">
                  <span style="margin-right: 10px;">+{{form.publisherAreaCode}}</span>
                  <span>{{form.publisherTel || '--'}}</span>

                  <!-- <areaTel v-model:firstValue="param.tel" v-model:secondValue="param.areaCode" style="width:100%;" disabled></areaTel> -->
                </div>
              </div>
            </div>
         </div>
      </div>
       <div class="mian-cen-list">
              <div class="mian-cen-item">
                <div class="item-label red-star">经办人：</div>
                <div class="item-value">{{ userInfo.nickname }}</div>
              </div>
        </div>  
         <div class="mian-cen-list" v-for="(item, index) in allocationList" :key="index">
              <div class="mian-cen-item">
                <div class="item-label red-star">业务员：</div>
                <el-select v-model="item.businessUserId" filterable clearable placeholder="请选择">
                  <el-option v-for="item in userSimple"
                      :key="item.userId"
                      :label="item.nickname"
                      :value="item.userId" />
                </el-select>
              </div>
               <div class="mian-cen-item">
                <div class="item-label red-star">操作员：</div>
                <el-select v-model="item.operateUserId" filterable clearable placeholder="请选择">
                  <el-option v-for="item in userSimple"
                      :key="item.userId"
                      :label="item.nickname"
                      :value="item.userId" />
                </el-select>
              </div>
              <div class="mian-cen-item flex-cen">
                <div class="item-label red-star">业务编号：</div>
                <el-input v-model.trim="item.businessNo" clearable style="width:100%;" maxlength="30" placeholder="请输入业务编号"></el-input>
                <el-icon color="#D8D8D8" size="20px" style="margin-left: 20px;" @click="handleDelete(index,2)"><Remove /></el-icon>
              </div>
        </div> 
        <div class="mian-cen-list">
              <div class="mian-cen-item">
                  <el-icon color="#2158F3" @click="handleAdd(2)" size="20px"><CirclePlus /></el-icon>
              </div>
        </div>        
        <div class="remak">
           <div class="remak-title">留言</div> 
           <el-input  placeholder="请输入内容" :formatter="containsEmoji" v-model="form.leaveMsg" show-word-limit type="textarea" maxlength="500" />
        </div> 
       
    </div>
   </el-card>
    <div class="foot">
        <div class="foot-list">
          <div style="margin-right: 20px;">
            <el-checkbox v-model="radioVal" size="large" />
          我已阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款
          </div>
          
        <el-button @click="handleSubmit" type="primary">提交订单</el-button>
        </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { computed, onActivated, reactive, ref,onBeforeMount } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { addBoxCallbackOrder} from '@/api/boxCallBack/order'
import { userSimpleList } from '@/api/user/index'
import {getBoxInfo } from '@/api/boxCallBack/index'
import { ElMessage } from 'element-plus';
import Cookies from "js-cookie";
import { formatterNumber,containsEmoji } from '@/utils'

const router = useRouter()
const route = useRoute()
const radioVal=ref(false)
const allIs=ref(true)
const allIsTap=()=>{
  allIs.value=!allIs.value
}

// 禁止选择过去日期（可以选择今天）
const disabledDate=(time)=> {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
  }
//总回调箱量
const totalHdBox = computed(() => {
  return param.allocation.reduce((acc, cur) => {
    return acc + cur.number
  }, 0)
})
const userSimple = ref([]) // 操作员列表
const userInfo=ref({}) //经办人个人信息
onActivated(() => {
  userInfo.value = JSON.parse(Cookies.get("User-Info"))
  getSetBoxInfo();
  userOperator()
})

// 获取数据
const mainFileList = ref([]) //图片
const dataInfo=ref({})
const form=ref({})
const allocationList=ref([{
    businessUserId:'',
    businessUserName:'',
    operateUserId:'',
    operateUserName:'',
    businessNo:'',
}])
const priceList=ref([{
  carryCityId:'',
  carryCityName:'',
  carryCountryId:'',
  carryCountryName:'',
  returnCityId:'',
  returnCityName:'',
  returnCountryId:'',
  returnCountryName:'',
  unitPrice:'',
  boxQuantity:0,
}])
const carryCityList=ref([]) //出发城市list
const returnCityList=ref([]) //到达城市list
const carryCityInfo=ref({}) // 出发城市初始化
const getSetBoxInfo = async () => {
  await getBoxInfo(route.query.orderId).then(async (res: any) => {
    form.value=res.data
    let data=res.data
    mainFileList.value = JSON.parse(data.mainFileList)
    carryCityList.value = JSON.parse(data.carryCity)
    carryCityInfo.value = carryCityList.value[0]
   
    returnCityList.value = JSON.parse(data.returnCity)

    if(route.query?.submitData){//详情
      let submitData=JSON.parse(route.query?.submitData)
      data.releaseCallbackPriceList.forEach((item,index) => {
        if(item.boxType==submitData.boxType && item.boxCondition==submitData.boxCondition){
         dataInfo.value= data.releaseCallbackPriceList[index]
         console.log(index,'iiiii')
        }
      })
      
    }else{//列表
      dataInfo.value= data.releaseCallbackPriceList[0]
    }
    priceList.value[0]={
       carryCityId:'',
      carryCityName:'',
      carryCountryId:'',
      carryCountryName:'',
      returnCityId:'',
      returnCityName:'',
      returnCountryId:'',
      returnCountryName:'',
      unitPrice:dataInfo.value.unitPrice,
      boxQuantity:0,
    }
  })
}

const totalNumber  = computed(() => {
  let num = 0
  if(priceList.value && priceList.value.length > 0){
    priceList.value.forEach((el) => {
      num =  el.boxQuantity + num
    })
  }
  return num
})
//添加
const handleAdd = (type) => {
  if(type==1){
     if(returnCityList.value.length==priceList.value.length){
      return ElMessage.warning("到达城市只要"+returnCityList.value.length+"个无需重复添加")
    }
     if (priceList.value.length == 10) return ElMessage.warning("最多新增10条数据")
      let data = priceList.value[priceList.value.length - 1] //新增 默认copy最后一行的数据
      let allocation = JSON.parse(JSON.stringify(data))
      allocation.returnCityId=''
      priceList.value.push(allocation)
  }else if(type==2){
    if (allocationList.value.length == 5) return ElMessage.warning("最多新增5条数据")
      let data = allocationList.value[allocationList.value.length - 1] //新增 默认copy最后一行的数据
      let allocation = JSON.parse(JSON.stringify(data))
      allocationList.value.push(allocation)
  }
}
//删除
const handleDelete = (index,type) => {
  if(type==1){
    if(priceList.value.length>1){
    priceList.value.splice(index, 1)
    }else{
      return ElMessage.warning("至少保留1条数据")
    }
  }else if(type==2){
    if(allocationList.value.length>1){
    allocationList.value.splice(index, 1)
    }else{
      return ElMessage.warning("至少保留1条数据")
    }
  }
  
}
//城市选择
const returnCityIdChang=(row,index)=>{
  let returnCityId=[]
  priceList.value.forEach((item: any) => {
    if(item.returnCityId!=''){
      returnCityId.push(item.returnCityId)
    }
  })
  let isReturnCityId =new Set(returnCityId).size !== returnCityId.length
  if(isReturnCityId){
    priceList.value[index].returnCityId=''
    return ElMessage.warning("存在到达城市重复的数据")
  }
}


const totalMoney = ref(0)
const computedPrice = computed(() => {
  let arry = param.allocation
  totalMoney.value = 0
  arry.forEach((el) => {
    if (el.number >= 0 && el.price >= 0) {
      el.xiaoJi = el.number * el.price
      totalMoney.value = totalMoney.value - 0 + el.xiaoJi
    }
  })
  return arry
})


//提交订单
const handleSubmit = async () => {
  let allocationIs=false
  if(!radioVal.value) return ElMessage.warning('请先阅读并同意《集装箱租赁业务规则》和《用户服务协议和管理规则》')
  if (!carryCityInfo.value.cityId) return ElMessage.warning('出发城市不能为空')
   priceList.value.forEach((el: any) => {
       if (el.unitPrice == '' || el.unitPrice<=0) {
          allocationIs=true
            return ElMessage.warning('箱贴单价不能为空切大于0')
        }   
         if (el.boxQuantity == '' || el.boxQuantity<=0) {
          allocationIs=true
            return ElMessage.warning('预还量不能为空切大于0')
        }   
          if (el.returnCityId == '') {
          allocationIs=true
            return ElMessage.warning('到达城市不能为空')
        }      
    })
  if(allocationIs){
    return false
  }
  if (!form.value.boxUsagePeriod) return ElMessage.warning('箱使期不能为空')
  if (!form.value.planPickupDate) return ElMessage.warning('预计提箱日期不能为空')
  if (!form.value.paymentMethod) return ElMessage.warning('支付方式不能为空')
      //操作人
   allocationList.value.forEach((el: any) => {  
        if (el.businessUserId == '') {
          allocationIs=true
            return ElMessage.warning('业务员不能为空')
        }     
        if (el.operateUserId == '') {
          allocationIs=true
          return ElMessage.warning('操作员不能为空')
        }
       
         if (el.businessNo == '') {
          allocationIs=true
            return ElMessage.warning('业务编号不能为空')
        }   
    })
  if(allocationIs){
    return false
  }
  handleSign()
}
// 签署
const handleSign = () => {
    priceList.value.forEach((el: any) => {
      returnCityList.value.forEach((item: any) => {
        if (el.returnCityId == item.cityId) {
          el.returnCityName = item.cityName
          el.returnCountryId = item.countryId
          el.returnCountryName = item.countryName
        }
      })
      
    })
    carryCityList.value.forEach((item: any) => {
        if (carryCityInfo.value.cityId == item.cityId) {
          carryCityInfo.value.cityName = item.cityName
          carryCityInfo.value.countryId = item.countryId
          carryCityInfo.value.countryName = item.countryName
        }
      })
      //操作人
   allocationList.value.forEach((el: any) => {
      userSimple.value.forEach((item: any) => {
        if (el.businessUserId == item.userId) {
          el.businessUserName = item.nickname
        }
        if (el.operateUserId == item.userId) {
          el.operateUserName = item.nickname
        }
      })
      
    })
  const data = {
    "releaseCallbackId": form.value.id,
    "carryCityId": carryCityInfo.value.cityId,
    "carryCityName": carryCityInfo.value.cityName,
    "carryCountryId": carryCityInfo.value.countryId,
    "carryCountryName": carryCityInfo.value.countryName,
    "boxType": dataInfo.value.boxType,
    "boxCondition": dataInfo.value.boxCondition,
    "currency":"USD",
    "planPickupDate": form.value.planPickupDate,
    "paymentMethod": form.value.paymentMethod,
    "contacts": form.value.publisherName,
    "tel": form.value.publisherTel,
    "boxUsagePeriod":form.value.boxUsagePeriod,
    "agentUserId": userInfo.value.id,
    "agentUserName":userInfo.value.nickname,
    "agentUserAreaCode":userInfo.value.areaCode,
    "agentUserTel":userInfo.value.mobile,
    "leaveMsg": form.value.leaveMsg,
    "allocation": JSON.stringify(allocationList.value),
    "callbackOrderPriceBeans": priceList.value,
    "period":form.value.period
  }
  addBoxCallbackOrder(data).then((res: any) => {
    router.push('agentMarketHuiDiaoBox')
    ElMessage.success('下单成功')
  })
}


// 数字格式化（保留两位小数）
const roundToTwoDecimals = (num:number) =>{
  return Math.round(num * 100) / 100;
}

// 查询操作员import { userSimpleList } from '@/api/user/index'
const  userOperator = ()=>{
  userSimpleList({}).then(res => {
    userSimple.value = res.data
    allocationList.value[0].operateUserId=userInfo.value.id

  })
}

</script>
<style lang="scss" scoped>
.lookUp{
  margin: 0 !important ;
  padding: 20px 0;
  span{
    height: 40px;
  }
}
.pag-container {
  margin-top: 20px;
  box-sizing: border-box;
  // padding: 10px;
}

.el-form--inline .el-form-item {
  margin-right: 8px;
}



.mian-cen-top{
  display: flex;
  margin-top: 20px;
}
.mian-cen-top-fr{
  flex: 1;
}
.mian-cen-list{
  display: flex;
  align-items: center;
  padding: 10px 0;
  // justify-content: space-between;
}
.mian-cen-item{
  display: flex;
  align-items: center;
  width: 30%;
  margin-right: 3%;
}
.item-label{
  width: 120px;
}
.item-value{
 flex:1,
}
.foot{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}
.foot-list{
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: center;
  background: #fff !important;
  padding: 20px 0;
  border-top: 1px solid #eeeeee;
  box-shadow: 0 -1px 0 0 #efefef;
}
.title-top-fl{
  font-weight: bold;
}
.xlMain{
  margin-top: 20px;
}
.xlMain-list{
  display: flex;
  padding: 10px 0;
}
.xlMain-lable{
  width: 21%;
  margin: 0 2%;
  text-align: center;
}
.remak-title{
  margin-bottom: 10px;
}
.app-container{
  padding-bottom: 100px;
}
.zlAmo{
  border-top: 1px solid #eeeeee;
  text-align: right;
  padding:20px 80px;
  margin-top: 20px;
}
</style>